package com.mxdx.edu.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.ModelAndView;

import com.mxdx.edu.common.ApiResult;
import com.mxdx.edu.common.AppException;
import com.mxdx.edu.common.CommonUtils;
import com.mxdx.edu.common.log.AppLogger;
import com.mxdx.edu.constant.StaticConstants;
import com.mxdx.edu.enums.ErrorEnums;
import com.mxdx.edu.service.ICacheService;
import com.mxdx.edu.service.IClassDocumentService;
import com.mxdx.edu.service.ISchoolStatusService;
import com.mxdx.edu.service.ISemesterService;
import com.mxdx.edu.service.ISerialService;
import com.mxdx.edu.service.IStudentService;
import com.mxdx.edu.service.IUserJobBasisSeekerService;
import com.mxdx.edu.util.RedisUtil;
import com.mxdx.edu.util.SessionUtil;
import com.mxdx.edu.util.SmsUtil;

/**
 * Controller基类
 *
 * @author wangyuan
 * @date 2016-11-24 15:57
 */
public class BaseController {

	@Resource
	protected SessionUtil sessionUtil;

	@Resource
	protected RedisUtil redisUtil;

	@Resource
	protected SmsUtil smsUtil;

	@Value("${appName}")
	protected String appName;

	@Value("${specialNum}")
	protected String specialNum;

	@Value("${imageHost}")
	protected String imageHost;

	@Value("${cmsImageHost}")
	protected String cmsImageHost;

	@Value("${smsLockExpireTime}")
	protected long smsLockExpireTime;

	@Value("${smsCacheLockExpireTime}")
	protected long smsCacheLockExpireTime;

	@Resource
	protected ISerialService serialService;

	@Resource
	protected IStudentService studentService;

	@Resource
	protected ISemesterService semesterService;

	@Resource
	protected ISchoolStatusService schoolStatusService;

	@Resource
	protected IClassDocumentService classDocumentService;

	@Resource
	protected ICacheService cacheService;

	@Resource
	protected IUserJobBasisSeekerService userJobBasisSeekerService;

	protected static int pageSize = 4;

	protected void dealAppExcetion(AppException e, ApiResult<?> apiResult,
			AppLogger logger) {
		String errorCode = e.getErrorCode();
		String msg = e.getMsg();
		apiResult.setStatus(errorCode);
		apiResult.setMessage(msg);
		logger.error(apiResult, e);
	}

	protected void dealException(ErrorEnums errorEnums, Exception e,
			ApiResult<?> apiResult, AppLogger logger) {
		apiResult.setStatus(errorEnums.getCode());
		apiResult.setMessage(errorEnums.getDesc());
		logger.error(apiResult, e);
	}

	/**
	 * 设置Resthub-Spec响应头部
	 *
	 * @param response
	 */
	@ModelAttribute
	protected void setHeader(HttpServletResponse response) {
		response.setHeader(StaticConstants.RESTHUB_SPEC,
				StaticConstants.RESTHUB_SPEC_V);
	}

	@SuppressWarnings("unchecked")
	protected String getStudentId(HttpServletRequest request) {
		String token = sessionUtil.getTokenSession(request);
		if (redisUtil.get(token) != null) {
			Map<String, Object> map = (Map<String, Object>) redisUtil.get(token);
			if (map.containsKey("studentId")) {
				return map.get("studentId").toString();
			}
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	protected Map<String, Object> getStudentMap(HttpServletRequest request) {
		String token = sessionUtil.getTokenSession(request);
		if (redisUtil.get(token) != null) {
			Map<String, Object> map = (Map<String, Object>) redisUtil
					.get(token);
			return map;
		}
		return null;
	}

	/**
	 * 验证日期格式
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isValidDate(String str) {
		boolean convertSuccess = true;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		try {
			format.setLenient(false);
			format.parse(str);
		} catch (ParseException e) {
			convertSuccess = false;
		}
		return convertSuccess;
	}

	/**
	 * 校验发送验证码是否获取过于频繁
	 *
	 * @param mobilePhone
	 * @return
	 */
	protected boolean isAlreadySend(int smsType, String mobilePhone) {
		String formatKey = String.format("%s_%s", smsType, mobilePhone);
		try {
			synchronized (this) {
				if (null == redisUtil.get(formatKey)) {
					return false;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}
	/**
	 * 校验发送验证码是否获取过于频繁
	 *
	 * @param mobilePhone
	 * @return
	 */
	protected boolean isAlreadySendCache(int smsType, String mobilePhone) {
		String formatKey = String.format("%s_%s_cache", smsType, mobilePhone);
		try {
			synchronized (this) {
				if (null == redisUtil.get(formatKey)) {
					return false;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

	protected void removeImgCode(String uuid) {
		redisUtil.delete(String.format("imageCode_%s", uuid));
	}

	public boolean checkSmsCode(String mobilePhone, String smsCode,
			int smsType) {
		Object smsCodeValue = null;
		String smsKey = String.format("%s_%s", smsType, mobilePhone);
		smsCodeValue = redisUtil.get(smsKey);
		// 验证码不正确
		if (smsCodeValue == null || !smsCodeValue.toString().equals(smsCode)) {
			return false;
		}
		return true;
	}

	public void getUserBasisInfo(String studentId, ModelAndView modelAndView) {
		Map<String, Object> param = new HashMap<>();
		param.put("studentId", studentId);
		Map<String, Object> studentMap = studentService.findStudentMapOneByMap(param);
		String headPortrait = CommonUtils.getStrValueFromMap(studentMap, "headPortrait", "");
		String studentName = CommonUtils.getStrValueFromMap(studentMap, "studentName", "");
		String mood = CommonUtils.getStrValueFromMap(studentMap, "mood", "");
		String recommendationCode = CommonUtils.getStrValueFromMap(studentMap, "recommendationCode", "");
		modelAndView.addObject("recommendationCode", recommendationCode);
		modelAndView.addObject("headPortrait", headPortrait);
		modelAndView.addObject("studentName", studentName);
		modelAndView.addObject("mood", mood);
	}
	public void getUserMapByToken(HttpServletRequest request, ModelAndView modelAndView) {
		String token = sessionUtil.getTokenSession(request);
		Map<String,Object> studentMap = (Map<String, Object>)redisUtil.get(token);
		String mood = CommonUtils.getStrValueFromMap(studentMap, "mood", "");
		String studentName = CommonUtils.getStrValueFromMap(studentMap, "studentName", "");
		String headPortrait = CommonUtils.getStrValueFromMap(studentMap, "headPortrait", "");
		String recommendationCode = CommonUtils.getStrValueFromMap(studentMap, "recommendationCode", "");
		modelAndView.addObject("mood", mood);
		modelAndView.addObject("recommendationCode", recommendationCode);
		modelAndView.addObject("studentName", studentName);
		modelAndView.addObject("headPortrait", headPortrait);
	}


	protected String getJobBasisId(HttpServletRequest request) {
		String studentId = getStudentId(request);
		Map<String, Object> userJobBasisMap = userJobBasisSeekerService.findBasisSeekByStudentId(studentId);
		return CommonUtils.getStrValueFromMap(userJobBasisMap, "id", "");
	}
}
